from daos import get_db_session, get_update_contents
from models.album_info import AlbumInfo


def add_album_info(model_orm: AlbumInfo, is_commit=True):
    session = get_db_session()

    session.add(model_orm)
    session.commit() if is_commit else session.flush()
    return model_orm


def query_album_info(pk):
    return get_db_session().query(AlbumInfo).filter(AlbumInfo.id == pk).first()



def update_album_info(user_orm: AlbumInfo, *args, is_commit=True):
    session = get_db_session()
    update_contents = get_update_contents(user_orm, *args)
    session.query(AlbumInfo).filter(AlbumInfo.id == user_orm.id).update(update_contents)
    session.commit() if is_commit else session.flush()
    return


def query_album_info_with_page(data_param):
    filter_s = []
    if data_param.get('title'):
        filter_s.append(AlbumInfo.title.contains(data_param.get('title')))

    if data_param.get('dy_album_id'):
        filter_s.append(AlbumInfo.dy_album_id == data_param.get('dy_album_id'))

    if data_param.get('release_year'):
        filter_s.append(AlbumInfo.release_year == data_param.get('release_year'))

    if data_param.get('album_status'):
        filter_s.append(AlbumInfo.album_status == data_param.get('album_status'))

    session = get_db_session()
    return session.query(AlbumInfo) \
        .filter(*filter_s) \
        .order_by(AlbumInfo.id.desc()) \
        .paginate(page=data_param.get('page'), per_page=data_param.get('page_size'), error_out=False)


def query_album_info_s(data_param):
    filter_s = []

    if data_param.get('title'):
        filter_s.append(AlbumInfo.title.contains(data_param.get('title')))

    if data_param.get('dy_album_id'):
        filter_s.append(AlbumInfo.dy_album_id == data_param.get('dy_album_id'))

    if data_param.get('release_year'):
        filter_s.append(AlbumInfo.release_year == data_param.get('release_year'))

    if data_param.get('album_status'):
        filter_s.append(AlbumInfo.album_status == data_param.get('album_status'))

    session = get_db_session()
    return session.query(AlbumInfo) \
        .filter(*filter_s) \
        .order_by(AlbumInfo.id.desc()) \
        .all()


def query_album_info_count(data_param):
    filter_s = []

    if data_param.get('title'):
        filter_s.append(AlbumInfo.title == data_param.get('title'))

    if data_param.get('dy_open_pic_id'):
        filter_s.append(AlbumInfo.dy_open_pic_id == data_param.get('dy_open_pic_id'))

    if data_param.get('status'):
        filter_s.append(AlbumInfo.status == data_param.get('status'))

    session = get_db_session()
    return session.query(AlbumInfo).filter(*filter_s).count()
